<!-- 工具表单弹窗 -->
<script setup lang="ts">
import type { ToolFormRule } from '@/api/tools';
import { ElMessage } from 'element-plus';
import { ref } from 'vue';
import { getToolDetail, submitToolForm } from '@/api/tools';

// 定义组件属性
const props = defineProps<{
  visible: boolean;
  toolId: number;
  toolName?: string;
}>();

// 定义事件发射器
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void;
  (e: 'submit', formData: Record<string, any>, responseData: { message: string; tool_id: number }): void;
  (e: 'cancel'): void;
}>();

// 表单数据
const formData = ref<Record<string, any>>({});
const formRules = ref<ToolFormRule[]>([]);
const loading = ref(false);
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => {
    emit('update:visible', val);
  },
});

// 上次获取数据的工具ID
const lastFetchedToolId = ref<number | null>(null);

// 获取工具详情
async function fetchToolDetail() {
  // 只有在弹窗可见且有toolId时才获取数据
  if (!props.visible || !props.toolId)
    return;

  // 避免重复请求相同工具的数据
  if (lastFetchedToolId.value === props.toolId && formRules.value.length > 0) {
    return;
  }

  loading.value = true;
  try {
    const response = await getToolDetail(props.toolId);
    if (response.code === 200) {
      formRules.value = response.data.form_rule.sort((a: any, b: any) => a.displayorder - b.displayorder);
      // 初始化表单数据
      formRules.value.forEach((rule) => {
        formData.value[rule.name] = '';
      });

      // 记录上次获取数据的工具ID
      lastFetchedToolId.value = props.toolId;
    }
    else {
      ElMessage.error(response.message || '获取工具详情失败');
    }
  }
  catch (error) {
    ElMessage.error('获取工具详情失败');
  }
  finally {
    loading.value = false;
  }
}

// 监听工具ID变化和弹窗可见性变化
watch([() => props.toolId, () => props.visible], ([newToolId, newVisible], [oldToolId]) => {
  // 当工具ID改变时，清空之前的数据
  if (newToolId !== oldToolId) {
    formRules.value = [];
    formData.value = {};
    lastFetchedToolId.value = null;
  }

  // 只有当弹窗变为可见时才获取数据
  if (newVisible && newToolId) {
    fetchToolDetail();
  }
}, { immediate: true });

// 提交表单
async function handleSubmit() {
  // 第一步：显示loading状态
  loading.value = true;

  try {
    // 第二步：POST调用接口system/tools/{id}
    const response = await submitToolForm(props.toolId, formData.value);

    // 第三步：返回成功后关闭弹窗和loading
    if (response.code === 200) {
      // 将响应数据传递给父组件，包括message和tool_id
      emit('submit', formData.value, {
        message: response.data.message,
        tool_id: response.data.tool_id,
      });
      dialogVisible.value = false;
    }
    else {
      ElMessage.error(response.message || '提交失败');
    }
  }
  catch (error) {
    ElMessage.error('提交失败');
  }
  finally {
    loading.value = false;
  }
}

// 取消表单
function handleCancel() {
  emit('cancel');
  dialogVisible.value = false;
}

// 计算是否需要显示label
const shouldShowLabel = computed(() => {
  // 如果只有一条规则且类型是textarea，则不显示label
  return !(formRules.value.length === 1 && formRules.value[0].type === 'textarea');
});

// 计算label宽度
const labelWidth = computed(() => {
  return shouldShowLabel.value ? '100px' : '0';
});
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="toolName || '工具表单'"
    class="tool-form-dialog"
    :width="800"
    :loading="loading"
    @close="handleCancel"
  >
    <el-form
      v-loading="loading"
      :model="formData"
      :label-width="labelWidth"
      style="padding: 20px 0;"
    >
      <el-row :gutter="20">
        <template v-for="rule in formRules" :key="rule.name">
          <el-col
            v-if="rule.type !== 'textarea'"
            :span="24"
            :md="12"
            class="mb-20px"
          >
            <el-form-item
              :label="shouldShowLabel ? rule.name : ''"
            >
              <!-- 文本输入框 -->
              <el-input
                v-if="rule.type === 'text'"
                v-model="formData[rule.name]"
                :placeholder="rule.remark || `请输入${rule.name}`"
              >
                <template v-if="rule.unit" #append>
                  {{ rule.unit }}
                </template>
              </el-input>

              <!-- 选择框 -->
              <el-select
                v-else-if="rule.type === 'select'"
                v-model="formData[rule.name]"
                :placeholder="rule.remark || `请选择${rule.name}`"
                style="width: 100%"
              >
                <el-option
                  v-for="option in rule.options?.split('|') || []"
                  :key="option"
                  :label="option"
                  :value="option"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col
            v-else
            :span="24"
            class="mb-20px"
          >
            <el-form-item
              :label="shouldShowLabel ? rule.name : ''"
            >
              <!-- 文本域 -->
              <el-input
                v-model="formData[rule.name]"
                type="textarea"
                :rows="rule.rows"
                :placeholder="rule.remark || `请输入${rule.name}`"
              />
            </el-form-item>
          </el-col>
        </template>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer" style="text-align: center;">
        <el-button @click="handleCancel">
          取消
        </el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.text-gray-500 {
  color: #999;
}
.text-xs {
  font-size: 12px;
}
.mt-1 {
  margin-top: 4px;
}
.mb-20px {
  margin-bottom: 20px;
}
</style>

<style lang="scss">
// 弹窗样式 - 需要使用全局样式才能正确覆盖Element Plus的默认样式
@media screen and (max-width: 768px) {
  .tool-form-dialog {
    width: 95vw !important;
    max-width: 95vw !important;
  }
}

@media screen and (max-width: 480px) {
  .tool-form-dialog {
    width: 98vw !important;
    max-width: 98vw !important;
    margin: 10px auto !important;
  }
}

// 限制内容区域的最大宽度
.tool-form-dialog .el-dialog__body {
  max-width: 100%;
  overflow-x: hidden;
}
</style>
